package com.huobi.pro.account;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.IntStream;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.huobi.db.bean.Account;
import com.huobi.db.mapper.AccountMapper;
import com.huobi.pro.trade.client.OrderRestClient;

@Service
public class AccountService {

	@Autowired OrderRestClient futurePostV1;
	@Autowired AccountMapper accountMapper;

	@Scheduled(cron = "0/10 * * * * ?")
	public void queryBalance() {
		accounts();
		//balance();
	}

	private void balance() {
		List<Account> accounts = accountMapper.selectAccount();
		accounts.forEach(va->{
			String res = futurePostV1.queryBalance(va.getAccountId());
			
			if(StringUtils.isEmpty(res))
				return;
			
			JSONObject obj = JSONObject.parseObject(res);
			String status = obj.getString("status");
			if("ok".equals(status)) {
				JSONObject data = obj.getJSONObject("data");
				JSONArray list = data.getJSONArray("list");
				IntStream.range(0, list.size()).forEach(value->{
					JSONObject account = list.getJSONObject(value);
					String currency = account.getString("currency");
					String type = account.getString("type");
					BigDecimal balance = account.getBigDecimal("balance");
					if("usdt".equals(currency) ) {
						if ("frozen".equals(type)) {
							va.setFrozenUsdt(balance);  va.setUpdateTime(new Date());
						}
						if ("trade".equals(type)) {
							va.setTradeUsdt(balance);  va.setUpdateTime(new Date());
						}
					}
				});
				// 更新账户信息
				accountMapper.update(va);
			}
		});
	}

	private void accounts() {
		
		String accountsStr = futurePostV1.accounts();
		
		if (StringUtils.isEmpty(accountsStr)) {
			return;
		}
		
		JSONArray array = JSONObject.parseObject(accountsStr).getJSONArray("data");
		List<Account> accounts = new ArrayList<Account>();

		for (int i = 0; i < array.size(); i++) {
			JSONObject ob = array.getJSONObject(i);
			String type = ob.getString("type");
			String id = ob.getString("id");

			Account account = new Account();
			account.setAccountId(id);
			account.setType(type);
			accounts.add(account);
		}

		accounts.forEach(v -> {
			Account acc = accountMapper.getAccount(v.getAccountId(), v.getType());
			if (acc == null) {
				v.setFrozenUsdt(BigDecimal.ZERO);
				v.setTradeUsdt(BigDecimal.ZERO);
				v.setUpdateTime(new Date());
				accountMapper.newAccount(v);
			}
		});
	}

	public Account getAccountId(String type) {
		return accountMapper.selectAccountByType(type);
	}

}
